#include "../include/header.h"

/**
 * 实现即时聊天，如果对方连续10s没有发送任何消息则断开连接。
 * （注意，即使本方在10s内从标准输入当中输入数据也不行）。
*/
int main(int argc, char* argv[]){
	ARGS_CHECK(argc, 1);
    int pipe_write = open("1.pipe", O_WRONLY);
	ERROR_CHECK(pipe_write, -1, "open write");
    int pipe_read = open("2.pipe", O_RDONLY);
	ERROR_CHECK(pipe_read, -2, "open read");

    fd_set set;
    FD_ZERO(&set);

    while(1){
        FD_SET(STDIN_FILENO, &set);
        FD_SET(pipe_read, &set);

        int res_select = select(10, &set, NULL, NULL, NULL);



        if(FD_ISSET(STDIN_FILENO, &set)){
            char buf[60] = {0};
            bzero(buf, sizeof(buf));
            read(STDIN_FILENO, buf, sizeof(buf));
            write(pipe_write, buf, sizeof(buf));
        }

        if(FD_ISSET(pipe_read, &set)){
            char buf[60] = {0}; 
            bzero(buf, sizeof(buf));
            int res = read(pipe_read, buf, sizeof(buf));
            if(res == 0){
                printf("对端关闭了管道 \n");
                break;
            }
            printf("B: %s \n", buf);
        }
    }

    close(pipe_read);
    close(pipe_write);

    return 0;

}